<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .list {
        width: 200px;
        height: 150px;
        background: cadetblue;
        overflow-y: auto;
      }
      .news {
        height: 30px;
      }
    </style>
  </head>
  <body>
    <div id="test"></div>
    <script src="../lib/17/react.js"></script>
    <script src="../lib/17/react-dom.js"></script>
    <script src="../lib/babel.min.js"></script>
    <script type="text/babel">
      class NewList extends React.Component {
        state = { newsArr: [] };
        componentDidMount() {
          this.timer = setInterval(() => {
            const { newsArr } = this.state;
            //模拟一条新闻
            const news = "新闻" + (newsArr.length + 1);
            //更新状态
            this.setState({ newsArr: [news, ...newsArr] });
          }, 500);
        }
        getSnapshotBeforeUpdate() {
          console.log(this.list.scrollHeight);
          return this.list.scrollHeight;
        }

        componentDidUpdate(preProps, preState, snotshot) {
          this.list.scrollTop += this.list.scrollHeight - snotshot;
        }
        render() {
          const { newsArr } = this.state;
          return (
            <div className="list" ref={(c) => (this.list = c)}>
              {newsArr.map((item, index) => {
                return <div key={index}>{item}</div>;
              })}
            </div>
          );
        }
      }
      ReactDOM.render(<NewList />, document.getElementById("test"));
    </script>
  </body>
</html>
